(function() {
    const OVERVIEW_CLASS = "shopify-order-overview";

    frappe.ui.form.on("Sales Order", {
        refresh(frm) {
            upsystem?.sales_order_shopify_overview?.render(frm);
        }
    });

    frappe.provide("upsystem.sales_order_shopify_overview");

    function ensure_overview_styles() {
        const STYLE_ID = 'shopify-overview-inline-styles';
        if (document.getElementById(STYLE_ID)) {
            return;
        }
        const css = `
.shopify-overview-card{width:100%;box-sizing:border-box;}
.std-form-layout .shopify-overview-card,.form-layout .shopify-overview-card{margin-left:-24px;margin-right:-24px;width:calc(100% + 48px);} 
@media (max-width:768px){.std-form-layout .shopify-overview-card,.form-layout .shopify-overview-card{margin-left:-12px;margin-right:-12px;width:calc(100% + 24px);}}
.shopify-overview-table-grid{width:100%;border-collapse:collapse;table-layout:fixed;}
.shopify-overview-table-grid td.grid-cell{width:50%;vertical-align:top;text-align:left;padding:0 16px 20px 0;}
.shopify-overview-table-grid tr td.grid-cell:nth-child(2){padding-right:0;padding-left:16px;}
`;
        const style = document.createElement('style');
        style.id = STYLE_ID;
        style.type = 'text/css';
        style.appendChild(document.createTextNode(css));
        document.head.appendChild(style);
    }

    upsystem.sales_order_shopify_overview.render = function(frm) {
        const rawField = frm.fields_dict?.custom_shop_raw_data;
        if (!rawField) {
            return;
        }

        hide_form_tabs(frm);
        ensure_overview_styles();

        const wrapper = get_or_create_overview_wrapper(frm);
        const rawPayload = frm.doc.custom_shop_raw_data;

        if (!rawPayload) {
            wrapper && wrapper.length && wrapper.hide();
            toggle_raw_field_visibility(rawField, true);
            return;
        }

        let payload;
        try {
            payload = JSON.parse(rawPayload);
        } catch (err) {
            wrapper
                .show()
                .html(
                    `<div class="shopify-overview-error">${__('无法解析 Shopify 原始数据。请检查 JSON 格式。')}</div>`
                );
            toggle_raw_field_visibility(rawField, true);
            return;
        }

        const html = build_overview_html(payload);
        wrapper && wrapper.length && wrapper.show().html(html);
        toggle_raw_field_visibility(rawField, false);
    };

    function get_or_create_overview_wrapper(frm) {
        const layoutWrapper = frm.layout?.wrapper;
        if (!layoutWrapper || !layoutWrapper.length) {
            return null;
        }

        let container = layoutWrapper.find(`.${OVERVIEW_CLASS}`);
        if (!container.length) {
            container = $(`<div class="${OVERVIEW_CLASS}"></div>`);
            const mainSection = layoutWrapper.find('.layout-main-section').first();
            if (mainSection && mainSection.length) {
                mainSection.prepend(container);
            } else {
                layoutWrapper.prepend(container);
            }
        }
        return container;
    }

    function hide_form_tabs(frm) {
        const layoutWrapper = frm.layout?.wrapper;
        if (!layoutWrapper || !layoutWrapper.length) {
            return;
        }
        layoutWrapper.find('.form-tabs').hide();
        layoutWrapper.find('.nav-tabs').hide();
    }

    function toggle_raw_field_visibility(field, showRaw) {
        const rawWrapper = field.$wrapper;
        if (!rawWrapper || !rawWrapper.length) {
            return;
        }

        const toggleBtnClass = "shopify-raw-toggle";
        let toggleBtn = rawWrapper.prev(`.${toggleBtnClass}`);

        if (!toggleBtn.length) {
            toggleBtn = $(
                `<div class="shopify-raw-toggle">
                    <button class="btn btn-xs btn-secondary" type="button">${__('查看原始 JSON')}</button>
                </div>`
            );
            rawWrapper.before(toggleBtn);
            toggleBtn.find("button").on("click", () => {
                rawWrapper.toggle();
                toggleBtn.toggleClass("is-open");
                const isVisible = rawWrapper.is(":visible");
                toggleBtn.find("button").text(
                    isVisible ? __('隐藏原始 JSON') : __('查看原始 JSON')
                );
            });
        }

        if (showRaw) {
            rawWrapper.show();
            toggleBtn.hide();
        } else {
            rawWrapper.hide();
            toggleBtn.show().removeClass("is-open");
            toggleBtn.find("button").text(__('查看原始 JSON'));
        }
    }

    function build_overview_html(payload) {
        const buyer = payload.customer || {};
        const shipping = payload.shippingAddress || {};
        const orderInfo = extract_order_info(payload);
        const warehouseInfo = extract_warehouse_info(payload);
        const lineItems = extract_order_items(payload);

        const shippingDetails = format_address_lines(shipping);
        if (warehouseInfo.length) {
            shippingDetails.push(...warehouseInfo);
        }
 
        const sections = [
            render_section(
                __('Order Summary'),
                [
                    orderInfo.created_at && `${__('Created At')}: <strong>${format_datetime(orderInfo.created_at)}</strong>`,
                    orderInfo.updated_at && `${__('Updated At')}: <strong>${format_datetime(orderInfo.updated_at)}</strong>`,
                    orderInfo.total_display && `${__('Order Total')}: <strong>${frappe.utils.escape_html(orderInfo.total_display)}</strong>`,
                    orderInfo.financial_status && `${__('Financial Status')}: <strong>${frappe.utils.escape_html(orderInfo.financial_status)}</strong>`,
                    orderInfo.fulfillment_status && `${__('Fulfillment Status')}: <strong>${frappe.utils.escape_html(orderInfo.fulfillment_status)}</strong>`,
                    orderInfo.tags && orderInfo.tags.length ? `${__('Tags')}: ${orderInfo.tags.map(frappe.utils.escape_html).join(', ')}` : ""
                ]
            ),
            render_items_section(lineItems),
            render_section(
                __('Buyer Information'),
                [
                    buyer.displayName && `${__('Name')}: <strong>${frappe.utils.escape_html(buyer.displayName)}</strong>`,
                    buyer.email && `${__('Email')}: <a href="mailto:${frappe.utils.escape_html(buyer.email)}">${frappe.utils.escape_html(buyer.email)}</a>`,
                    buyer.phone && `${__('Phone')}: <strong>${frappe.utils.escape_html(buyer.phone)}</strong>`,
                    buyer.locale && `${__('Language')}: <strong>${frappe.utils.escape_html(buyer.locale)}</strong>`
                ]
            ),
            render_section(
                __('Shipping & Warehouse'),
                shippingDetails.length ? shippingDetails : [__('No shipping information')]
            )
        ];

        return `
            <div class="shopify-overview-card">
                <div class="shopify-overview-header">
                    <div class="title">${__('Shopify 订单概览')}</div>
                    <div class="meta">
                        ${orderInfo.id ? `<span class="badge">${frappe.utils.escape_html(orderInfo.id)}</span>` : ""}
                        ${orderInfo.status ? `<span class="badge status">${frappe.utils.escape_html(orderInfo.status)}</span>` : ""}
                    </div>
                </div>

                <table class="shopify-overview-table-grid">
                    <tbody>
                        <tr>
                            <td class="grid-cell">${sections[0]}</td>
                            <td class="grid-cell">${sections[1]}</td>
                        </tr>
                        <tr>
                            <td class="grid-cell">${sections[2]}</td>
                            <td class="grid-cell">${sections[3]}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        `;
    }

    function render_section(title, rows, extraClass = '') {
        const validRows = (rows || []).filter(Boolean);
        if (!validRows.length) {
            return "";
        }
        return `
            <div class="shopify-overview-section ${extraClass}">
                <div class="section-title">${frappe.utils.escape_html(title)}</div>
                <ul class="section-list">
                    ${validRows
                        .map(row => `<li>${row}</li>`)
                        .join("")}
                </ul>
            </div>
        `;
    }

    function extract_order_info(payload) {
        return {
            id: payload.name || payload.id,
            status: payload.displayFulfillmentStatus || payload.fulfillmentStatus,
            created_at: payload.createdAt,
            updated_at: payload.updatedAt,
            total_display: format_total(payload),
            financial_status: payload.displayFinancialStatus || payload.financialStatus,
            fulfillment_status: payload.displayFulfillmentStatus || payload.fulfillmentStatus,
            tags: Array.isArray(payload.tags) ? payload.tags : []
        };
    }

    function extract_order_items(payload) {
        const nodes = (payload.lineItems && payload.lineItems.nodes) || [];
        if (!Array.isArray(nodes) || !nodes.length) {
            return [];
        }

        return nodes.map(node => {
            const variant = node.variant || {};
            const price = node.discountedTotal || node.originalTotal || '';
            const sku = variant.sku || node.sku || '';
            return {
                title: node.name || node.title || __('未命名商品'),
                variant: node.variantTitle || '',
                sku,
                quantity: node.quantity || 0,
                price
            };
        });
    }

    function render_items_section(items, extraClass = '') {
        if (!items.length) {
            return '';
        }

        const rows = items.map(item => {
            return `
                <tr>
                    <td class="item-title">
                        ${frappe.utils.escape_html(item.title)}
                        ${item.variant ? `<div class="item-variant">${frappe.utils.escape_html(item.variant)}</div>` : ''}
                    </td>
                    <td>${frappe.utils.escape_html(item.sku || '-')}</td>
                    <td>${frappe.utils.escape_html(String(item.quantity))}</td>
                    <td>${frappe.utils.escape_html(item.price || '-')}</td>
                </tr>
            `;
        }).join('');

        return `
            <div class="shopify-overview-section shopify-overview-items ${extraClass}">
                <div class="section-title">${__('Line Items')}</div>
                <div class="items-table-wrapper">
                    <table class="items-table">
                        <thead>
                            <tr>
                                <th>${__('Product')}</th>
                                <th>${__('SKU')}</th>
                                <th>${__('Qty')}</th>
                                <th>${__('Amount')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${rows}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    }

    function extract_warehouse_info(payload) {
        const edges = payload.fulfillmentOrders && payload.fulfillmentOrders.edges;
        if (!Array.isArray(edges) || !edges.length) {
            return [];
        }

        return edges.map(edge => {
            const node = edge && edge.node ? edge.node : {};
            const location = node.assignedLocation || {};
            const status = node.status || "";
            const name = location.name || "";
            const parts = [];
            if (name) {
                parts.push(`${__('仓库')}: <strong>${frappe.utils.escape_html(name)}</strong>`);
            }
            if (status) {
                parts.push(`${__('状态')}: ${frappe.utils.escape_html(status)}`);
            }
            return parts.join(" &nbsp;•&nbsp; ") || __('履约单信息缺失');
        });
    }

    function format_address_lines(address) {
        if (!address || typeof address !== "object") {
            return [];
        }

        const lines = [];
        const name = [address.firstName, address.lastName].filter(Boolean).join(" ") || address.name;
        if (name) {
        lines.push(`${__('Recipient')}: <strong>${frappe.utils.escape_html(name)}</strong>`);
        }
        if (address.phone) {
        lines.push(`${__('Phone')}: <strong>${frappe.utils.escape_html(address.phone)}</strong>`);
        }
        if (address.address1 || address.address2) {
        lines.push(`${__('Address')}: ${frappe.utils.escape_html([address.address1, address.address2].filter(Boolean).join(', '))}`);
        }
        if (address.city || address.province || address.zip) {
        lines.push(`${__('City/State/Zip')}: ${frappe.utils.escape_html([address.city, address.province, address.zip].filter(Boolean).join(', '))}`);
        }
        if (address.country) {
        lines.push(`${__('Country')}: ${frappe.utils.escape_html(address.country)}${address.countryCode ? ` (${frappe.utils.escape_html(address.countryCode)})` : ""}`);
        }
        return lines;
    }

    function format_datetime(value) {
        if (!value) {
            return "";
        }
        try {
            const sysdefaults = frappe.boot?.sysdefaults || {};
            const dateFmt = sysdefaults.date_format || "YYYY-MM-DD";
            const timeFmt = sysdefaults.time_format || "HH:mm";
            return frappe.datetime.moment(value).format(`${dateFmt} ${timeFmt}`);
        } catch (err) {
            return frappe.utils.escape_html(value);
        }
    }

    function format_total(payload) {
        if (!payload) {
            return "";
        }
        const total = payload.totalPrice || payload.subtotalPrice;
        if (!total) {
            return "";
        }
        const currency = payload.presentmentCurrencyCode || payload.currencyCode;
        return currency ? `${total} ${currency}` : `${total}`;
    }
})();


